package pyip.lib.javalearn.algorithm;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public abstract class Cache {

    private final Map<Object, Object> store;
    private int initialCapacity = 16;
    private float loadFactor = 0.75f;
    private int maxCapacity;

    public Cache(boolean accessOrder, final int maxCapacity) {
        final Cache _this = this;
        this.maxCapacity = maxCapacity;
        this.store = new LinkedHashMap<Object, Object>(initialCapacity, loadFactor, accessOrder) {
            private static final long serialVersionUID = -3834209229668463829L;

            @Override
            protected boolean removeEldestEntry(Entry<Object, Object> eldest) {
                return size() > _this.maxCapacity;
            }
        };
    }

    public void add(Object k, Object v) {
        store.put(k, v);
    }

    public Object get(Object k) {
        return store.get(k);
    }

    public Collection<Object> getAll() {
        return store.values();
    }

    public int getMaxCapacity() {
        return maxCapacity;
    }

    public void setMaxCapacity(int maxCapacity) {
        this.maxCapacity = maxCapacity;
    }

}